using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model;
using WPF_MVVM_Test.Services;

namespace WPF_MVVM_Test.MVVM_ViewModel
{
    public class MesAiChatViewModel : BaseViewModel
    {
        private readonly MesAiService _mesAiService;
        private string _currentMessage = string.Empty;
        private bool _isAiTyping = false;
        private bool _isServiceHealthy = false;
        private string _serviceStatus = "检查中...";
        private ChatMessage? _currentAiMessage;

        public MesAiChatViewModel()
        {
            _mesAiService = new MesAiService();
            ChatMessages = new ObservableCollection<ChatMessage>();

            SendMessageCommand = CreateCommand(ExecuteSendMessage, () => CanSendMessage);
            ClearChatCommand = CreateCommand(ExecuteClearChat);
            RefreshServiceCommand = CreateCommand(ExecuteRefreshService);
            TestConnectionCommand = CreateCommand(ExecuteTestConnection);

            // 启动时检查服务健康状态
            _ = CheckServiceHealthAsync();
        }

        public ObservableCollection<ChatMessage> ChatMessages { get; }

        public string CurrentMessage
        {
            get => _currentMessage;
            set
            {
                SetProperty(ref _currentMessage, value);
                OnPropertyChanged(nameof(CanSendMessage));
            }
        }

        public bool IsAiTyping
        {
            get => _isAiTyping;
            set
            {
                SetProperty(ref _isAiTyping, value);
                OnPropertyChanged(nameof(CanSendMessage));
            }
        }

        public bool IsServiceHealthy
        {
            get => _isServiceHealthy;
            set => SetProperty(ref _isServiceHealthy, value);
        }

        public string ServiceStatus
        {
            get => _serviceStatus;
            set => SetProperty(ref _serviceStatus, value);
        }

        public bool CanSendMessage => !string.IsNullOrWhiteSpace(CurrentMessage) && !IsAiTyping && IsServiceHealthy;

        public ICommand SendMessageCommand { get; }
        public ICommand ClearChatCommand { get; }
        public ICommand RefreshServiceCommand { get; }
        public ICommand TestConnectionCommand { get; }

        private async Task CheckServiceHealthAsync()
        {
            try
            {
                ServiceStatus = "正在检查服务状态...";

                // 尝试多次检查，因为服务可能响应较慢
                for (int attempt = 1; attempt <= 3; attempt++)
                {
                    System.Diagnostics.Debug.WriteLine($"健康检查尝试 {attempt}/3");
                    ServiceStatus = $"正在检查服务状态... (尝试 {attempt}/3)";

                    IsServiceHealthy = await _mesAiService.CheckHealthAsync();

                    if (IsServiceHealthy)
                    {
                        ServiceStatus = "服务正常";
                        AddWelcomeMessage();
                        break;
                    }

                    // 如果不是最后一次尝试，等待一段时间再重试
                    if (attempt < 3)
                    {
                        ServiceStatus = $"服务检查失败，{3 - attempt} 秒后重试...";
                        await Task.Delay(3000); // 等待3秒
                    }
                }

                if (!IsServiceHealthy)
                {
                    ServiceStatus = "服务不可用 - 请检查网络连接";
                    AddServiceUnavailableMessage();
                }

                // 通知CanSendMessage属性更新
                OnPropertyChanged(nameof(CanSendMessage));
            }
            catch (Exception ex)
            {
                ServiceStatus = "服务检查失败";
                IsServiceHealthy = false;
                System.Diagnostics.Debug.WriteLine($"健康检查异常: {ex.Message}");
                AddServiceUnavailableMessage();
                OnPropertyChanged(nameof(CanSendMessage));
            }
        }

        private void AddWelcomeMessage()
        {
            ChatMessages.Add(new ChatMessage
            {
                Content = "您好！我是MES智能助手，专门为您的制造执行系统提供智能支持。服务已就绪，有什么可以帮助您的吗？",
                IsUser = false,
                Timestamp = DateTime.Now
            });
        }

        private void AddServiceUnavailableMessage()
        {
            ChatMessages.Add(new ChatMessage
            {
                Content = "抱歉，MES智能助手服务当前不可用。请检查网络连接或稍后再试。",
                IsUser = false,
                Timestamp = DateTime.Now
            });
        }

        private void ExecuteClearChat()
        {
            ChatMessages.Clear();
            if (IsServiceHealthy)
            {
                AddWelcomeMessage();
            }
            else
            {
                AddServiceUnavailableMessage();
            }
        }

        private async void ExecuteRefreshService()
        {
            ChatMessages.Clear();
            await CheckServiceHealthAsync();
        }

        private async void ExecuteSendMessage()
        {
            if (string.IsNullOrWhiteSpace(CurrentMessage) || IsAiTyping || !IsServiceHealthy)
                return;

            var userMessage = CurrentMessage.Trim();
            CurrentMessage = string.Empty;

            // 添加用户消息
            ChatMessages.Add(new ChatMessage
            {
                Content = userMessage,
                IsUser = true,
                Timestamp = DateTime.Now
            });

            // 设置AI正在输入状态
            IsAiTyping = true;

            // 创建AI消息占位符
            _currentAiMessage = new ChatMessage
            {
                Content = "正在思考中...",
                IsUser = false,
                Timestamp = DateTime.Now
            };

            ChatMessages.Add(_currentAiMessage);

            // 强制更新UI
            OnPropertyChanged(nameof(ChatMessages));

            try
            {
                System.Diagnostics.Debug.WriteLine($"发送MES AI消息: {userMessage}");

                var request = new MesAiRequest
                {
                    Content = userMessage
                };

                // 设置超时 - 5分钟
                var timeoutTask = Task.Delay(300000); // 5分钟 = 300000毫秒
                var requestTask = _mesAiService.SendMessageAsync(
                    request,
                    GetCurrentUserId(), // 将userId作为单独参数传递
                    OnDataReceived,
                    OnCompleted,
                    OnError
                );

                // 等待请求完成或超时
                if (await Task.WhenAny(requestTask, timeoutTask) == timeoutTask)
                {
                    // 请求超时
                    System.Diagnostics.Debug.WriteLine("MES AI请求超时");
                    OnError(new TimeoutException("请求超时，服务器响应时间过长。"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"发送MES AI消息异常: {ex}");
                OnError(ex);
            }
        }

        private void OnDataReceived(string data)
        {
            // 确保在UI线程上执行
            Application.Current.Dispatcher.Invoke(() =>
            {
                System.Diagnostics.Debug.WriteLine($"收到MES AI回复: '{data}'");

                if (_currentAiMessage != null)
                {
                    if (!string.IsNullOrWhiteSpace(data))
                    {
                        // 直接更新当前消息内容
                        _currentAiMessage.Content = data;

                        // 强制通知UI更新
                        OnPropertyChanged(nameof(ChatMessages));

                        System.Diagnostics.Debug.WriteLine("MES AI消息已更新");
                    }
                    else
                    {
                        _currentAiMessage.Content = "抱歉，我暂时无法回答这个问题。";
                        OnPropertyChanged(nameof(ChatMessages));
                    }
                }
            });
        }

        private void OnCompleted()
        {
            // 确保在UI线程上执行
            Application.Current.Dispatcher.Invoke(() =>
            {
                IsAiTyping = false;
                System.Diagnostics.Debug.WriteLine("MES AI响应完成");
            });
        }

        private void OnError(Exception ex)
        {
            // 确保在UI线程上执行
            Application.Current.Dispatcher.Invoke(() =>
            {
                IsAiTyping = false;

                if (_currentAiMessage != null)
                {
                    _currentAiMessage.Content = $"抱歉，发生了错误：{ex.Message}";
                    OnPropertyChanged(nameof(ChatMessages));
                }

                System.Diagnostics.Debug.WriteLine($"MES AI错误: {ex.Message}");
            });
        }

        private string? GetCurrentUserId()
        {
            // 这里可以从当前登录用户获取ID
            // 暂时返回null，让服务端使用默认值
            // 如果需要获取当前登录用户ID，可以从Application.Current.Properties或其他地方获取
            return null;
        }

        private async void ExecuteTestConnection()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("=== 开始测试MES AI连接 ===");

                // 添加测试消息
                ChatMessages.Add(new ChatMessage
                {
                    Content = "正在测试API连接...",
                    IsUser = false,
                    Timestamp = DateTime.Now
                });

                var result = await _mesAiService.TestApiConnectionAsync();

                ChatMessages.Add(new ChatMessage
                {
                    Content = result ? "✅ API连接测试成功！" : "❌ API连接测试失败，请检查网络或服务状态。",
                    IsUser = false,
                    Timestamp = DateTime.Now
                });

                OnPropertyChanged(nameof(ChatMessages));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"测试连接异常: {ex.Message}");
                ChatMessages.Add(new ChatMessage
                {
                    Content = $"❌ 连接测试异常: {ex.Message}",
                    IsUser = false,
                    Timestamp = DateTime.Now
                });
                OnPropertyChanged(nameof(ChatMessages));
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _mesAiService?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
